<template>
  <div class="place-order">
    <div class="form-card">
      <h2 class="form-title">预约回收</h2>
      <el-form :model="formState" :rules="rules" ref="formRef" label-width="120px">
        <!-- 地址选择 -->
        <el-form-item label="选择地址" prop="addressId">
          <el-select 
            v-model="formState.addressId"
            placeholder="请选择地址"
            @change="handleAddressChange"
          >
            <el-option
              v-for="addr in addresses"
              :key="addr.addressId"
              :value="addr.addressId"
              :label="`${addr.detailedAddress} (${addr.city} ${addr.district})`"
              :selected="addr.isDefault === 1"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 联系人信息 -->
        <el-form-item label="联系人姓名" prop="appointName">
          <el-input v-model="formState.appointName" placeholder="请输入联系人姓名"></el-input>
        </el-form-item>

        <el-form-item label="联系电话" prop="appointPhone">
          <el-input v-model="formState.appointPhone" placeholder="请输入联系电话"></el-input>
        </el-form-item>

        <!-- 预约时间 -->
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker
            v-model="formState.appointmentTime"
            type="datetime"
            placeholder="选择预约时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>

        <!-- 预估重量 -->
        <el-form-item label="预估重量(kg)" prop="estimate_weight">
          <el-input-number 
            v-model="formState.estimate_weight"
            :min="0.01"
            :max="1000"
            :precision="2"
            :step="0.01"
            placeholder="请输入预估重量">
          </el-input-number>
        </el-form-item>

        <!-- 备注信息 -->
        <el-form-item label="备注信息" prop="remarks">
          <el-input
            type="textarea"
            v-model="formState.remarks"
            :rows="3"
            placeholder="请输入备注信息（选填）">
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitOrder" :loading="submitting">提交订单</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Message } from 'element-ui'
import axios from 'axios'

interface Address {
  addressId: number
  userId: number
  latitude: number
  longitude: number
  city: string
  district: string
  street: string
  detailedAddress: string
  isDefault: number
}

const addresses = ref<Address[]>([])
const formRef = ref()
const submitting = ref(false)

const formState = ref({
  addressId: undefined as number | undefined,
  appointName: '',
  appointPhone: '',
  appointmentTime: '',
  estimate_weight: 1,
  remarks: '',
  city: '',
  district: '',
  street: '',
  detailedAddress: '',
  latitude: 0,
  longitude: 0,
})

const rules = {
  addressId: [{ required: true, message: '请选择地址', trigger: 'change' }],
  appointName: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
  appointPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  appointmentTime: [{ required: true, message: '请选择预约时间', trigger: 'change' }],
  estimate_weight: [{ required: true, message: '请输入预估重量', trigger: 'change' }],
}

const pickerOptions = {
  disabledDate(time: Date) {
    return time.getTime() < Date.now() - 8.64e7 // 不能选择过去的日期
  },
  selectableRange: '08:00:00 - 20:00:00' // 可选时间范围
}

// 获取用户地址列表
const fetchAddresses = async () => {
  try {
    const response = await axios.get('/userService/address/selectAddressByUserId',{
      params:{
        userId:localStorage.getItem('userId')
      }
    })
    if (response.data.code === 200) {
      addresses.value = response.data.data
      
      // 设置默认地址
      const defaultAddress = addresses.value.find(addr => addr.isDefault === 1)
      if (defaultAddress) {
        formState.value.addressId = defaultAddress.addressId
        handleAddressChange(defaultAddress.addressId)
      }
    }
  } catch (error) {
    Message.error('获取地址列表失败')
  }
}

// 地址选择改变处理
const handleAddressChange = (value: number) => {
  const selectedAddress = addresses.value.find(addr => addr.addressId === value)
  if (selectedAddress) {
    formState.value = {
      ...formState.value,
      addressId: value,
      city: selectedAddress.city,
      district: selectedAddress.district,
      street: selectedAddress.street,
      detailedAddress: selectedAddress.detailedAddress,
      latitude: selectedAddress.latitude,
      longitude: selectedAddress.longitude,
    }
  }
}

// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
}

// 提交订单
const submitOrder = async () => {
  try {
    await (formRef.value as any).validate()
    submitting.value = true
    const userId = localStorage.getItem('userId')
    const orderData = {
      ...formState.value,
      userId: Number(userId)
    }
    console.log(orderData)
    // const response = await axios.post('/recycle/recyclingOrder/addRecyclingOrde', orderData)
    // if (response.data.code === 200) {
    //   Message.success('下单成功')
    //   window.location.href = '/user/orders'
    // } else {
    //   Message.error(response.data.message || '提交订单失败')
    // }
  } catch (error) {
    Message.error('提交订单失败')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  fetchAddresses()
})
</script>

<style scoped>
.place-order {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.form-card {
  max-width: 800px;
  margin: 0 auto;
  background-color: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.form-title {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
  font-size: 24px;
}

.el-select {
  width: 100%;
}

.el-date-picker {
  width: 100%;
}

.el-textarea {
  width: 100%;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-button {
  padding: 12px 20px;
}

.el-button + .el-button {
  margin-left: 10px;
}
</style> 